package com.vhly.classfile;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class ConstantValue
        implements Attribute {

    /**
     * 指定到相应的常数项
     * 可以指向的类型为
     * byte, short, char,int, boolean -> CPInteger
     * long -> CPLong
     * float -> CPFloat
     * double -> CPDouble
     * java.lang.String -> CPString
     */
    private int vindex;
    /**
     * 名称，指向 ConstantValue (CPUtf8)
     */
    private int name_index;
    /**
     * 数据长度，始终是2
     */
    private int data_len;

    public ConstantValue() {
        name_index = 0;
        data_len = 2;
        vindex = 0;
    }

    public ConstantValue(int nameIndex, int dataLength, int valueIndex) {
        name_index = nameIndex;
        data_len = dataLength;
        vindex = valueIndex;
    }

    public int getValueIndex() {
        return vindex;
    }

    public void setValueIndex(int i) {
        vindex = i;
    }

    public void setNameIndex(int i) {
        name_index = i;
    }

    public int getNameIndex() {
        return name_index;
    }

    public void setDataLen(int i) {
        data_len = i;
    }

    public int getDataLen() {
        return data_len;
    }

    public void read(DataInputStream datainputstream, boolean flag)
            throws IOException {
        if (flag)
            name_index = datainputstream.readUnsignedShort();
        data_len = datainputstream.readInt();
        vindex = datainputstream.readUnsignedShort();
    }

    public void write(DataOutputStream dataoutputstream)
            throws IOException {
        dataoutputstream.writeShort(name_index);
        dataoutputstream.writeInt(data_len);
        dataoutputstream.writeShort(vindex);
    }

    public int getType() {
        return 2;
    }
}